// v-number-only:2="{precision:2}"
export default {
  inserted(el, options) {
    let content;
    el.addEventListener('keypress', event => {
      let e = event || window.event;
      let inputKey = String.fromCharCode(typeof e.charCode === 'number' ? e.charCode : e.keyCode);
      let re = /\d|\./;
      content = e.target.value;

      function preventInput() {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }

      if (!re.test(inputKey) && !e.ctrlKey) {
        preventInput();
      } else if (content.indexOf('.') > 0 && inputKey === '.') {
        preventInput();
      }
    });

    el.addEventListener('keyup', event => {
      let e = event || window.event;
      content = parseFloat(e.target.value);
      if (!content) {
        content = 0;
      }
      let arg_max = '';
      let arg_min = '';
      if (options.value) {
        arg_max = parseFloat(options.value.max);
        arg_min = parseFloat(options.value.min);
      }
      if (arg_max && content > arg_max) {
        e.target.value = arg_max;
        content = arg_max;
      }
      if (arg_min && content < arg_min) {
        e.target.value = arg_min;
        content = arg_min;
      }
    });
    //失去焦点=>保留指定位小数
    el.addEventListener('focusout', event => {
      let e = event || window.event;
      content = parseFloat(e.target.value);
      if (content) {
        if (('' + content).indexOf('.') >= 0 && options.value.precision >= 0) {
          console.log('content', content, parseFloat(options.value.precision));
          e.target.value = content.toFixed(parseFloat(options.value.precision));
        } else {
          e.target.value = content;
        }
      } else {
        e.target.value = 0;
      }
    });
  }
};
